﻿using System;
using System.Collections.Specialized;
using System.Reflection;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using VitCode.BaseDataPageCreator;
using VitCode.Castle.DataAccess;
using VitCode.Castle.Helper;
using VitCode.Castle.Management;
using VitCode.ObjectResolutionHelper;
using VitCode.Web.UI; 
using VitCode.BaseDataPageCreator.Setting; 

namespace VitCode.Web.BaseData
{
    public partial class ObjList : VcPage
    {
        private readonly CreateControlHelper m_CreateCtlHlp = new CreateControlHelper();
        private PageBuilder m_PageBuilder;
        readonly PermissionManager psManager = new PermissionManager();
        private CastleAccess m_CastleAccess = new CastleAccess();
        private ObjXmlReader m_XmlReader;
        PageLoadHelper pageLoadHelper = new PageLoadHelper();
        private UserDataSourceBuilder DataSourceBuilder
        {
            get { return (UserDataSourceBuilder)Session["DataSourceBuilder"]; }
            set { Session["DataSourceBuilder"] = value; }
        }

        private string SettingXmlPath
        {
            get { return AppDomain.CurrentDomain.BaseDirectory + "Setting\\BaseDataSet.xml"; }
        }

        private string ClassName
        {
            get { return m_CreateCtlHlp.ReturnQueryStringValue("ClassName",this); }
        }

        private string TypeName
        {
            get { return m_CreateCtlHlp.ReturnQueryStringValue("TypeName",this); }
            set { TypeName = value; }
        }

        private string MenuId
        {
            get { return m_CreateCtlHlp.ReturnQueryStringValue("MenuId", this); }
        }

        private string QueryCondition
        {
            get
            {
                
                if (ViewState["QueryCondition"] != null)
                    return ViewState["QueryCondition"].ToString();
                else
                    return "";
            }
            set { ViewState["QueryCondition"] = value; }
        }


        protected override void OnInit(EventArgs e)
        {
            Response.Expires = -1;
            if (m_PageBuilder == null)
                m_PageBuilder = new PageBuilder(this,SettingXmlPath);
            NavigateCtl1.SettingXmlPath = SettingXmlPath;
            if (TypeName.Length > 0)
                m_PageBuilder.SetPgListAttribute(pgList, ClassName, TypeName);
            else
                m_PageBuilder.SetPgListAttribute(pgList, ClassName);
              if(pgList.Columns[0] is PaginationGridCheckColumn)
              {
               if(!psManager.CheckPageIsCanDelete(this))
                   pgList.Columns.Remove(0);
                 
              }
            base.OnInit(e);
        }

        private void SetTimingIsUsePageCtl()
        {
            if (m_XmlReader == null) m_XmlReader = new ObjXmlReader(SettingXmlPath);
            var conditionInfo = m_XmlReader.GetNodeAttributeValue(ClassName, TypeName,
                                                                                    BaseDataKeyInfo.
                                                                                        TIMING_IS_USE_CONDITION_INFO,
                                                                                    true);
            var isTimingIsUse = conditionInfo.Length > 0;
            lblIsUseMemo.Visible = isTimingIsUse;
            ddlIsUse.Visible = isTimingIsUse;
            if(isTimingIsUse)
            {
                var ss = conditionInfo.Split(':');
                if(ss.Length == 2)
                {
                    var itemVals = ss[1].Split('|');
                    if(itemVals.Length > 0)
                    {
                        ddlIsUse.Items.Clear();
                        for (var i = 0; i < itemVals.Length; i++)
                            ddlIsUse.Items.Add(itemVals[i]);
                        ddlIsUse.Items.Add(new ListItem("全部", ""));
                        lblIsUseMemo.Text = ss[0];
                    }
                }
                
            }
        }

        private void CheckBtnVisible()
        {
            if (SettingXmlPath != "")
            {
                
                m_XmlReader = new ObjXmlReader(SettingXmlPath);
                var strAddValue = m_XmlReader.GetNodeAttributeValue(ClassName, TypeName, BaseDataKeyInfo.PAGE_CAN_ADD, true);
                btnAdd.Visible = (strAddValue.ToLower() != "false");
                var strDeleteValue = m_XmlReader.GetNodeAttributeValue(ClassName, TypeName, BaseDataKeyInfo.PAGE_CAN_DELETE, true);
                btnRealDelete.Visible = (strDeleteValue.ToLower() != "false");
                
                
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(GenericContext.CurrUserCode))
            {
                Response.Redirect("../Default.aspx");
            }

            Response.Write("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
            pgList.DataSourceBuilderDelegate = new PaginationGrid.GridDataSourceBuilderDelegate(BindPgList);
            if (!IsPostBack)
            {
                //PagePermissionHelper.CheckIsLoginToDefault(this);
                m_CreateCtlHlp.SetDdlCondition(pgList,ddlCondition);
                btnAdd.Visible = psManager.CheckPageIsCanAdd(this);
                btnRealDelete.Visible = psManager.CheckPageIsCanDelete(this);
                SetTimingIsUsePageCtl();
                
                //var v = System.Net.(Request.UserHostAddress);
                //v.AddressList.l
                if (SettingXmlPath != "")
                {
                    var strIsBindData = m_XmlReader.GetNodeAttributeValue(ClassName, TypeName, BaseDataKeyInfo.ISBINDDATA,
                                                                          true);
                    if (strIsBindData.ToLower() == "true")
                    {
                        QueryCondition = QueryHelper.GetQueryCondition(ddlCondition.SelectedValue, txtValue.Text, rbtAmount.Checked);
                        QueryCondition += GetIsUseCondition();
                        ListBind();
                    }
                }
            }
            CheckBtnVisible();
            
        }

        private void ListBind()
        {
            pgList.BindGrid();
            bool isCanDelete = (DataSourceBuilder.PrimaryKeys!=null && DataSourceBuilder.PrimaryKeys.Count > 0);
            btnRealDelete.Enabled = isCanDelete;
            btnRealDelete.Visible = psManager.CheckPageIsCanDelete(this);
            CheckBtnVisible();
        }

        private string GetIsUseCondition()
        {
            var isUseCondition = "";
            
            if (lblIsUseMemo.Visible && ddlIsUse.SelectedValue.Length > 0)
            {
                if (QueryCondition.Length > 0)
                    isUseCondition += " and ";
                else
                    isUseCondition += " where ";
                isUseCondition += " " + lblIsUseMemo.Text + "='" + ddlIsUse.SelectedValue + "'";
            }
            return isUseCondition;
        }

        private UserDataSourceBuilder BindPgList()
        {
            string sql = m_PageBuilder.GetPgListSqlValue(ClassName, TypeName);
            sql = sql.Replace("\r\n", " ").Replace("\t", " ");
            if (sql.IndexOf("{0}") > -1)
                sql = sql.Replace("{0}", TypeName);
            sql += " " + QueryCondition;
            DataSourceBuilder = new UserDataSourceBuilder(sql, pgList);
            return DataSourceBuilder;
        }

        protected void pgList_OnGridItemSelect(object sender, PaginationGridItemSelectArgs e)
        {
          
            Response.Redirect("ObjEdit.aspx?MenuId="+MenuId+"&ClassName=" + ClassName + "&TypeName=" + TypeName + "&" +
                              m_PageBuilder.GetPageKeyField(ClassName) + "=" +
                              e.SelectedDataKeyValue,false);
        }

        protected void btnRealDelete_Click(object sender, EventArgs e)
        {
            string strDelVal = pgList.GetSelectedItem(1);
            if(string.IsNullOrEmpty(strDelVal.Trim()))
            {
                Alert.MessageBox("請選擇要刪除的項!");
                return;
            }
            var cch = new CreateControlHelper();
            Type classType = m_PageBuilder.m_LoadHelper.GetClassTypeByClassNodeName(ClassName);
            string proName = m_PageBuilder.GetPageKeyField(ClassName);
            PropertyInfo pi = classType.GetProperty(proName);
            var acc = new BaseDataAccess();
            acc.BeginTransaction();
            try
            {
                StringCollection sc = acc.DeleteReErrMsg(false, strDelVal, pi.PropertyType, classType);
                
                if (sc.Count == 0)
                {acc.Commit();
                Alert.MessageBox("徹底刪除成功");
                }
                else
                {
                    var sb = new StringBuilder();
                    sb.Append("部分資料不能刪除,原因如下:\r\n");
                    for (int i = 0; i < sc.Count; i++)
                    {
                        string str = sc[i];
                        cch.SetDeleteErrMsgEachClassMemo(ref str);
                        sb.Append(str + "\r\n");
                    }
                    acc.RollBack();
                    Alert.MessageBox(sb.ToString());
                }
                ListBind();
            }
            catch(Exception ex)
            {
                acc.RollBack();
                throw;
            }
            finally
            {
                acc.CloseSession();
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            
            string editUrl = "ObjEdit.aspx?MenuId=" + MenuId + "&ClassName=" + ClassName;
            if (TypeName.Length > 0)
                editUrl += "&TypeName=" + TypeName;
            editUrl += "&Operate=Add";
            Response.Redirect(Server.UrlPathEncode(editUrl));
        }


        protected void btnQuery_Click(object sender, EventArgs e)
        {
            QueryCondition = QueryHelper.GetQueryCondition(ddlCondition.SelectedValue, txtValue.Text, rbtAmount.Checked);
            QueryCondition += GetIsUseCondition();
            ListBind();
        }

        protected void ConditionSelector1_SelectCondition(SelectConditionEventArgs e)
        {
            QueryCondition = null;
            if (!string.IsNullOrEmpty(ConditionSelector1.SelectedConditionString))
            QueryCondition = " where " + ConditionSelector1.SelectedConditionString;
            QueryCondition += GetIsUseCondition();
            ListBind();
        }

        protected void ddlIsUse_SelectedIndexChanged(object sender, EventArgs e)
        {
            QueryCondition = QueryHelper.GetQueryCondition(ddlCondition.SelectedValue, txtValue.Text, rbtAmount.Checked);
            QueryCondition += GetIsUseCondition();
            ListBind();
        }
    }
}
